<template>
  <div  class="page-map page-frame">
    <div class="page-frame-body">
      <!--地图部分-->
      <div ref="map" v-bind:style="{ width: width+'px', height:height + 'px' }"  id="map"></div>
    </div>
    <nav-toolbars data="2"></nav-toolbars>
  </div>
</template>

<script>
import Interface from "../GlobalData";
import { Toast, Indicator } from "mint-ui";
import NavToolbars from "@/components/navigation.vue";
export default {
  name: "Map",
  data() {
    return {
      width: 750,
      height: 1344,
      lat: 0,
      lng: 0,
      deviceList: [
        {
          lat: 30.28529,
          lng: 120.151269,
          id: "121"
        },
        {
          lat: 30.284419,
          lng: 120.149982,
          id: "122"
        },
        {
          lat: 30.277711,
          lng: 120.154252,
          id: "123"
        }
      ]
    };
  },
  components: {
    NavToolbars
  },
  created() {
    // 重新设置地图的宽高
    var map = $("#map");
    var wid = map.width();
    var hei = map.height();

    this.width = wid;
    this.height = hei;

    var self = this;
    self.Indicator.open("初始化地图...");

    var geolocation = new qq.maps.Geolocation(config.key, config.str);
    // 腾讯地图获取坐标
    geolocation.getLocation(
      function(res) {
        self.Indicator.close();
        var latitude = res.lat; // 纬度，浮点数，范围为90 ~ -90
        var longitude = res.lng; // 经度，浮点数，范围为180 ~ -180。

        self.lat = latitude;
        self.lng = longitude;

        // 初始化地图
        self.initMap(latitude, longitude);
      },
      function(e) {
        console.log(e);
      }
    );

    // 微信内置获取坐标
    // wx.ready(function() {
    //   wx.getLocation({
    //     type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    //     success: function(res) {
    //       self.Indicator.close();

    //       var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
    //       var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
    //       var speed = res.speed; // 速度，以米/每秒计
    //       var accuracy = res.accuracy; // 位置精度

    //       self.lat = latitude;
    //       self.lng = longitude;

    //       // 初始化地图
    //       self.initMap(latitude, longitude);
    //     }
    //   });
    // });
  },
  mounted() {},
  methods: {
    initMap(lat, lon) {
      var self = this;
      //设置地图中心点
      var myLatlng = new qq.maps.LatLng(lat, lon);

      //定义工厂模式函数
      var myOptions = {
        zoom: 13, //设置地图缩放级别
        center: myLatlng, //设置中心点样式
        mapTypeId: qq.maps.MapTypeId.ROADMAP, //设置地图样式详情参见MapType
        mapZoomType: qq.maps.MapZoomType.DEFAULT,
        noClear: false,
        scrollwheel: true,
        zoomControl: false,
        keyboardShortcuts: false,
        disableDoubleClickZoom: false,
        mapTypeControl: false,

        //地图比例尺控件，若为false则不显示比例尺控件
        scaleControl: false,
        //地图比例尺控件参数
        scaleControlOptions: {
          position: qq.maps.ControlPosition.BOTTOM_LEFT
        }
      };

      //获取dom元素添加地图信息
      window.myMap = new qq.maps.Map(document.getElementById("map"), myOptions);

      //当地图中心属性更改时会触发此事件。
      qq.maps.event.addListener(myMap, "center_changed", function(res) {
        //根据当前的地图中心坐标，更新附近的设备列表
        // self.initMapMarket(30.28529,120.151269);
      });

      // 设置当前位置的覆盖物
      self.initMapMarket(lat, lon);

      self.initMapEleData();
    },
    initMapEleData() {
      var self = this;
      $.ajax({
        url: Interface.host,
        type: "GET",
        data: self.getQeury({
          lat: self.lat,
          lon: self.lng
        }),
        beforeSend: () => {
          Indicator.open({
            text: "加载中...",
            spinnerType: "fading-circle"
          });
        },
        success: res => {
          Indicator.close();
          var data = res.data;
          self.deviceList = data.nearbySites;
          self.initMapEle();
        },
        error: err => {
          console.log(err);
          Toast("服务器开小差了~");
        }
      });
    },
    GoCenter(lat, lng) {
      /*地图切回到当前坐标位置*/
      var self = this;
      var lat = self.lat;
      var lng = self.lng;
      console.log(lat, lng);
      var myLatlng = new qq.maps.LatLng(lat, lng);
      myMap.setCenter(myLatlng);
      myMap.zoomTo(13);
    },
    initMapMarket(lat, lng) {
      var self = this;
      var myLatlng = new qq.maps.LatLng(lat, lng);
      //创建一个Marker
      var marker = new qq.maps.Marker({
        //设置Marker的位置坐标
        position: myLatlng,
        zIndex: 10,
        //设置显示Marker的地图
        map: myMap
      });

      //设置Marker的可见性，为true时可见,false时不可见，默认属性为true
      marker.setVisible(true);
      //设置Marker的动画属性为从落下
      // marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
      //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
      marker.setDraggable(false);
      ////设置Marker自定义图标的属性，size是图标尺寸，该尺寸为显示图标的实际尺寸，
      // origin是切图坐标，该坐标是相对于图片左上角默认为（0,0）的相对像素坐标，anchor是锚点坐标，描述经纬度点对应图标中的位置
      var anchor = new qq.maps.Point(25, 28),
        size = new qq.maps.Size(40, 40),
        origin = new qq.maps.Point(0, 0),
        icon = new qq.maps.MarkerImage(
          "https://ysc.mmcai.cn/web/imgs/icon-local.png",
          size,
          origin,
          anchor
        );
      marker.setIcon(icon);
    },
    initMapEle() {
      var self = this;
      var dataObjDevices = {};
      self.deviceList.forEach(function(ele) {
        var arr = [];
        arr.push(ele.lat);
        arr.push(ele.lon);
        dataObjDevices[ele.id] = arr;
      }, this);

      var Map = qq.maps.Map;
      var Marker = qq.maps.Marker;
      var LatLng = qq.maps.LatLng;
      var Event = qq.maps.event;

      var MarkerImage = qq.maps.MarkerImage;
      var MarkerShape = qq.maps.MarkerShape;
      var MarkerAnimation = qq.maps.MarkerAnimation;
      var Point = qq.maps.Point;
      var Size = qq.maps.Size;
      var ALIGN = qq.maps.ALIGN;

      var MVCArray = qq.maps.MVCArray;
      var MarkerCluster = qq.maps.MarkerCluster;
      var Cluster = qq.maps.Cluster;
      var MarkerDecoration = qq.maps.MarkerDecoration;

      var markers = new MVCArray();
      var markerCluster;

      function createCluster() {
        for (var k in dataObjDevices) {
          var d = dataObjDevices[k];
          var latLng = new LatLng(d[0], d[1]);
          //var decoration = new MarkerDecoration(i, new Point(0, -5));
          var marker = new Marker({
            position: latLng,
            map: myMap,
            id: k
          });

          var anchor = new qq.maps.Point(16, 18),
            size = new qq.maps.Size(32, 32),
            origin = new qq.maps.Point(0, 0),
            icon = new qq.maps.MarkerImage(
              "https://ysc.mmcai.cn/web/imgs/icon-e.png",
              size,
              origin,
              anchor
            );
          marker.setIcon(icon);
          //标记Marker点击事件
          qq.maps.event.addListener(marker, "click", function(data) {
            console.log(data.target);
            //self.$router.push("deviceInfo");
            self.$router.push({
              path: "deviceInfo",
              query: { id: data.target.id }
            });
          });

          markers.push(marker);
        }

        var markerClusterer = new MarkerCluster({
          map: myMap,
          minimumClusterSize: 100, //默认2
          markers: markers,
          zoomOnClick: true, //默认为true
          gridSize: 30, //默认60
          averageCenter: true, //默认false
          maxZoom: 16 //默认18
        });
      }

      createCluster();
    },
    getQeury({ lat, lon, level = 1 }) {
      return {
        query: `{
            nearbySites(lat:${lat},lon:${lon},level:${level}){
                  id
                  name
                  lat
                  lon
            }
          }`
      };
    },
    GoCharge() {
      /*跳转到充电主页*/
      // this.$router.push("charge");

      wx.ready(function() {
        wx.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
          success: function(res) {
            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          }
        });
      });
    },
    GoAccount() {
      /*跳转到我的帐号页面*/
      this.$router.push("account");
    }
  }
};
</script>


<style lang="less" scoped>
.page-index {
  position: relative;
  width: 100%;
  height: 100%;
}

#map {
  position: absolute;
  width: 100%;
  height: 100%;
}

.btn-location {
  position: absolute;
  z-index: 100;
  left: 32px;
  bottom: 90px;
  border-radius: 50%;
  width: 80px;
  height: 80px;
  background: #fff;
  -webkit-box-sizing: border-box;
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  box-shadow: 0 0 5px #999;
}

.loc-inner {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  border: 2px solid #00ac64;
  background: url("../public/imgs/icon-dot.png") 0 0 no-repeat;
  background-size: cover;
  text-align: center;
  color: #00ac64;
}

.btn-charge {
  position: absolute;
  z-index: 100;
  left: 50%;
  bottom: 110px;
  -webkit-transform: translate(-50%, 0);
  width: 300px;
  height: 80px;
  border-radius: 40px;
  background: #00ac64;
  color: #fff;
  text-align: center;
  line-height: 80px;
  font-size: 28px;
}

.btn-account {
  position: absolute;
  z-index: 100;
  right: 0;
  bottom: 90px;
  width: 100px;
  height: 80px;
  border-radius: 40px 0 0 40px;
  background: #fff;
  box-sizing: border-box;
  padding: 8px 8px 0 12px;
  box-shadow: 0 0 5px #999;
}

.acc-inner {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: url("../public/imgs/icon-account.png") center no-repeat;
  background-size: cover;
}
</style>
